package com.chunfeng.mypen.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.filter.Filter;
import com.chunfeng.mypen.result.exception.ServiceException;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.util.Objects;

/**
 * FastJson序列化配置
 *
 * @author by 春风能解释
 * <p>
 * 2023/11/23
 */
public class Fastjson2RedisSerializer<T> implements RedisSerializer<T> {

    /**
     * 指定可以自动序列化类的前缀(包名)
     */
    private static Filter AUTO_SERIALIZER_PREFIX = JSONReader.autoTypeFilter(
            "com.chunfeng.mypen.entity.***",//实体类
            "com.chunfeng.mypen.auth.***"//权限实体
    );
    /**
     * 序列化的类型字节码
     */
    private final Class<T> clazz;

    public Fastjson2RedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    /**
     * 将对象序列化为字节数组
     *
     * @param t 待序列化的对象
     * @return 序列化后的字节
     */
    @Override
    public byte[] serialize(T t) throws SerializationException {
        //对象为空
        if (Objects.isNull(t)) {
            return new byte[0];
        }
        try {
            //反序列化
            return JSON.toJSONBytes(t);
        } catch (Exception e) {
            throw new ServiceException(e.getLocalizedMessage());
        }
    }

    /**
     * 反序列化对象
     *
     * @param bytes 待反序列化的字节
     * @return 反序列化后的对象
     */
    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        // 判空
        if (bytes == null || bytes.length < 1) {
            return null;
        }
        try {
            //反序列化
            return JSON.parseObject(bytes, clazz, AUTO_SERIALIZER_PREFIX);
        } catch (Exception e) {
            throw new ServiceException(e.getLocalizedMessage());
        }
    }
}
